package cn.gov.pbc.gd.credit.user.service.realuser.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.liu.jbase.PageListVo;
import com.liu.jbase.ResultVo;
import com.liu.jbase.annotation.LogAnnotation;
import com.liu.jbase.constant.ResCode;
import com.liu.jbase.service.impl.BaseServiceImpl;
import com.liu.tools.LogUtil;
import com.liu.tools.NetHelper;
import com.liu.tools.PrimaryUtil;
import com.liu.tools.RandomUtil;
import com.liu.tools.StrUtil;
import com.liu.tools.pinyin.HanyuPinyinHelper;

import cn.gov.pbc.gd.credit.api.realuser.IRealUserApi;
import cn.gov.pbc.gd.credit.center.service.user.ICCUserService;
import cn.gov.pbc.gd.credit.common.constant.CodeConstant;
import cn.gov.pbc.gd.credit.common.constant.LogConstant;
import cn.gov.pbc.gd.credit.common.model.UserModel;
import cn.gov.pbc.gd.credit.common.service.redis.IRedisService;
import cn.gov.pbc.gd.credit.common.util.UserUtil;
import cn.gov.pbc.gd.credit.user.service.realuser.IRealUserService;
import cn.gov.pbc.gd.credit.vo.center.ReqCCUserVo;
import cn.gov.pbc.gd.credit.vo.center.ResCCUserVo;
import cn.gov.pbc.gd.credit.vo.realuser.RealUserVo;
import cn.gov.pbc.gd.credit.vo.realuser.ResRealUserVo;

@Service
public class RealUserServiceImpl extends BaseServiceImpl<ResRealUserVo, RealUserVo, IRealUserApi> implements IRealUserService{
	
	private static Logger logger = LoggerFactory.getLogger(RealUserServiceImpl.class);
	
	@Autowired
	private IRealUserApi realUserApi;
	
	@Autowired
	private IRedisService redisService;

	@Autowired
	private ICCUserService ccUserService;
	
	@LogAnnotation(moduleName=LogConstant.MODULE_REAL_USER, option=LogConstant.ADD, logType=LogConstant.LOG_OPERATE, content="添加真实用户")
	@Override
	public ResultVo<ResRealUserVo> add(RealUserVo realUserVo, HttpServletRequest request) {
		
		ResultVo<ResRealUserVo> resultVo = new ResultVo<>();
		if (realUserVo == null || StrUtil.isNull(realUserVo.getUserName(),realUserVo.getAccount(), realUserVo.getCorpId(),realUserVo.getOfficePhone())||realUserVo.getCorpId()==null) {
			
			logger.error(LogUtil.msg("RealUserServiceImpl:add", "请求参数不正确"));
			resultVo.setCode(ResCode.REQ_PARAM_FAIL);
			resultVo.setMsg("请求参数不正确");
			return resultVo;
		}
		
		realUserVo.setId(PrimaryUtil.primaryId("U"));
		realUserVo.setCreateIp(NetHelper.getIpAddr(request));
		realUserVo.setNamePinyin(HanyuPinyinHelper.toHanyuPinyin(realUserVo.getUserName()));
		realUserVo.setCreateTime(new Date());
		realUserVo.setUpdateTime(new Date());
		realUserVo.setProposerId(UserUtil.getUserModel(realUserVo.getSid(), redisService).getUserId());
		realUserVo.setApplyTime(new Date());
		realUserVo.setUpdatePwdTime(new Date());
		resultVo.setCode(CodeConstant.FAIL);
		try {
			int flag = realUserApi.insert(realUserVo);
			if(flag > 0){
				resultVo.setCode(CodeConstant.SUCCESS);
			} 
		} catch (Exception e) {
			logger.error(LogUtil.msg("RealUserServiceImpl:add", "添加真实用户异常"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
		}

		return resultVo;
	}
	
	@Override
	public ResultVo<List<ResRealUserVo>> list(RealUserVo record, HttpServletRequest request) {
		
		UserModel userModel = UserUtil.getUserModel(record.getSid(), redisService);
		
		record.setCorpId(userModel.getCorpId());
		
		return super.list(record, request);
	}
	
	@LogAnnotation(moduleName=LogConstant.MODULE_REAL_USER, option=LogConstant.UPDATE, logType=LogConstant.LOG_OPERATE, content="修改真实用户")
	@Override
	public ResultVo<ResRealUserVo> update(RealUserVo realUserVo, HttpServletRequest request) {
		ResultVo<ResRealUserVo> resultVo = new ResultVo<>();
		if (realUserVo == null) {
			logger.error(LogUtil.msg("RealUserServiceImpl:update", "请求参数不正确"));
			resultVo.setCode(ResCode.REQ_PARAM_FAIL);
			resultVo.setMsg("请求参数不正确");
			return resultVo;
		}
		
		realUserVo.setApplyTime(new Date());
		realUserVo.setUpdateTime(new Date());
		
		resultVo.setCode(CodeConstant.FAIL);
		try {
			int flag = realUserApi.update(realUserVo);
			if(flag > 0){
				resultVo.setCode(CodeConstant.SUCCESS);
			} 
		} catch (Exception e) {
			logger.error(LogUtil.msg("RealUserServiceImpl:add", "修改真实用户异常"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
		}
		return resultVo;
	}
	@LogAnnotation(moduleName=LogConstant.MODULE_REAL_USER, option=LogConstant.DEL, logType=LogConstant.LOG_OPERATE, content="删除真实用户")
	@Override
	public ResultVo<ResRealUserVo> delete(RealUserVo record, HttpServletRequest request) {
		// TODO Auto-generated method stub
		return super.delete(record, request);
	}
	
	@Override
	public ResultVo<ResRealUserVo> login(String realUserId, String userId, HttpServletRequest request) {
		
		ResultVo<ResRealUserVo> resultVo = new ResultVo<>();
		
		ResRealUserVo resRealUserVo = realUserApi.queryById(realUserId);
		
		ReqCCUserVo loginVo = new ReqCCUserVo();
		loginVo.setPassword(resRealUserVo.getUserPwd());
		loginVo.setUserid(resRealUserVo.getAccount());
		try {
			ResultVo<ResCCUserVo> resultLogin = ccUserService.login(loginVo, request);
			if(! CodeConstant.SUCCESS.equals(resultLogin.getCode())){
				
				if(CodeConstant.MODIFY_CC_PASSWORD.equals(resultLogin.getCode())){
					
					String password = RandomUtil.randomStr(11);
					logger.info(LogUtil.msg("UserServiceImpl:login", "开始修改征信中心密码,randomStr=" + password));
					
					ReqCCUserVo ccUserVo = new ReqCCUserVo();
					ccUserVo.setOldpassword(resRealUserVo.getUserPwd());
					ccUserVo.setNewpasswordvalid(password);
					ccUserVo.setPassword(password);
					ccUserVo.setCookies(resultLogin.getData().getCookies());
					ccUserVo.setUserid(resRealUserVo.getAccount());
					ResultVo<ResCCUserVo> modifyResult = ccUserService.froceModifyPwd(ccUserVo, request);
					if(! CodeConstant.SUCCESS.equals(modifyResult.getCode())){
						logger.error(LogUtil.msg("UserServiceImpl:login", "修改征信中心密码失败, modifyResult=" + JSON.toJSONString(modifyResult)));
						resultVo.setCode(CodeConstant.FAIL);
						resultVo.setMsg("登录征信中心账号失败，需要修改征信中心账户密码");
						return resultVo;
					}
					
					logger.info(LogUtil.msg("UserServiceImpl:login", "修改征信中心密码成功，开始修改真实用户密码"));
					
					RealUserVo realUserVo = new RealUserVo();
					realUserVo.setId(resRealUserVo.getId());
					realUserVo.setUserPwd(password);
					int flag = realUserApi.update(realUserVo);
					if(flag == 0){
						logger.error(LogUtil.msg("UserServiceImpl:login", "修改真实用户密码失败"));
						resultVo.setCode(CodeConstant.FAIL);
						resultVo.setMsg("修改真实用户密码失败");
						return resultVo;
					}
					
					logger.info(LogUtil.msg("UserServiceImpl:login", "修改真实用户密码成功,重新登录征信中心"));	
					loginVo.setPassword(password);
					resultLogin = ccUserService.login(loginVo, request);
					if(! CodeConstant.SUCCESS.equals(resultLogin.getCode())){
						logger.error(LogUtil.msg("UserServiceImpl:login", "登录征信中心失败realUserId=" + realUserId));
						resultVo.setCode(CodeConstant.FAIL);
						resultVo.setMsg("登录征信中心失败");
						if (StrUtil.isNotNull(resultLogin.getMsg())) {
							resultVo.setMsg(resultLogin.getMsg());
						}
						return resultVo;
					}
					
					ResCCUserVo resLoginVo = resultLogin.getData();			
					UserUtil.setRealUserLogin(resRealUserVo.getAccount(), userId, resLoginVo, redisService);
					resultVo.setCode(CodeConstant.SUCCESS);
					resultVo.setData(resRealUserVo);
					
					return resultVo;
				} else {
					
					logger.error(LogUtil.msg("UserServiceImpl:login", "登录征信中心失败realUserId=" + realUserId));
					resultVo.setCode(CodeConstant.FAIL);
					resultVo.setMsg("登录征信中心失败");
					if (StrUtil.isNotNull(resultLogin.getMsg())) {
						resultVo.setMsg(resultLogin.getMsg());
					}
					return resultVo;
				}
				
			}
			
			ResCCUserVo resLoginVo = resultLogin.getData();			
			UserUtil.setRealUserLogin(resRealUserVo.getAccount(), userId, resLoginVo, redisService);
			
		} catch (Exception e) {
			
			logger.error(LogUtil.msg("UserServiceImpl:login", "登录征信中心失败realUserId=" + realUserId), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
			resultVo.setMsg("登录征信中心异常");
			return resultVo;
		}
		resultVo.setCode(CodeConstant.SUCCESS);
		resultVo.setData(resRealUserVo);
		
		return resultVo;
	}
	
	@Override
	public ResultVo<PageListVo<ResRealUserVo>> page(RealUserVo record, PageListVo<ResRealUserVo> page,
			HttpServletRequest request) {

		UserModel userModel = UserUtil.getUserModel(record.getSid(), redisService);
		
		record.setCorpId(userModel.getCorpId());
		return super.page(record, page, request);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public ResultVo<List<RealUserVo>> queryAllRealUserWithOutUser(String userId) {
		ResultVo resultVo=new ResultVo();
		List<ResRealUserVo> realUserList=realUserApi.queryAllRealUserWithOutUser(userId);
		if(realUserList!=null&&realUserList.size()>0){
			resultVo.setCode("SUCCESS");
			resultVo.setData(realUserList);
		}else{
			resultVo.setCode("NO RESULT");
		}
		return resultVo;
	}

	@Override
	public void updateRealUser(RealUserVo realUserVo,HttpServletRequest request) {
		super.update(realUserVo, request);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public ResultVo<List> queryRealUserByUserId(String id) {
		ResultVo resultVo=new ResultVo(); 
		List<ResRealUserVo> realUserList=realUserApi.queryRealUserByUserId(id);
		resultVo.setData(realUserList);
		return resultVo;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public ResultVo queryThisUserShowLoginNameOrNot(String userName) {
		ResultVo resultVo=new ResultVo(); 
		List<ResRealUserVo>realUserList=realUserApi.queryThisUserShowLoginNameOrNot(userName);
		if(realUserList!=null&&realUserList.size()>1){
			resultVo.setCode("SUCCESS");
		}else{
			resultVo.setCode("FAIL");
		}
		return resultVo;
	}
}
